package org.example.sentineldemo.SentinelDemo;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created with IntelliJ IDEA 2023.
 * Description:
 * User: homechen
 * Date: 2024-05-02
 * Time: 21:03
 */
@RestController
@RequestMapping("/user")
public class Sentinel {

    // 通过代码定义资源
    @RequestMapping("/getuser")
    public String getUser() {
        try (Entry entry = SphU.entry("getUser")) {   // 定义资源
            Thread.sleep(2000);
            return "GetUser";
        } catch (Exception e) {
            return "被限流了!";
        }
    }

    // 通过注解定义资源
    @SentinelResource(value = "getUserById", blockHandler = "myBlockHandler")     // 执行拒绝策
    @RequestMapping("/getuserbyid")
    public String getUserById(Integer id) {
        return "GetUserById - " + id;
    }

    public String myBlockHandler(Integer id, BlockException blockException) {
        // 参数必须跟资源一致
        String msg = "Do myBlockHandler method";
        return msg;
    }
}
